﻿using System.Security.Cryptography;

namespace Common.Class
{
    public class FileHelper
    {
        /// <summary>
        /// 获取程序运行目录
        /// </summary>
        /// <returns></returns>
        public static string GetRunPath()
        {
            return System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
        }

        /// <summary>
        /// 获取文件夹中所有文件路径
        /// </summary>
        /// <param name="strDirPath">文件夹路径</param>
        /// <returns></returns>
        public static List<FileData> GetDirectoryFile(string strDirPath)
        {
            if (Directory.Exists(strDirPath))
            {
                List<FileData> _fileDataList = new List<FileData>();
                DirectoryInfo _directoryInfo = new DirectoryInfo(strDirPath);
                foreach (FileSystemInfo _fi in _directoryInfo.GetFileSystemInfos())
                {
                    if (_fi is FileInfo)
                    {
                        _fileDataList.Add(new FileData
                        {
                            FileName = _fi.FullName,
                            FileSize = (_fi as FileInfo).Length,
                            LastUpdateTime = _fi.LastWriteTimeUtc,
                        });
                    }
                }

                return _fileDataList;
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static FileData GetFileInfo(string filePath)
        {
            FileInfo _fileInfo = new FileInfo(filePath);
            return new FileData
            {
                FileName = _fileInfo.FullName,
                FileSize = (_fileInfo as FileInfo).Length,
                LastUpdateTime = _fileInfo.LastWriteTimeUtc,
            };

        }

        /// <summary>
        /// 获取文件夹所有子文件夹
        /// </summary>
        /// <param name="strDirPath">文件夹路径</param>
        /// <returns></returns>
        public static List<string> GetDirectorySubDirectory(string strDirPath)
        {
            if (Directory.Exists(strDirPath))
            {
                List<string> _directoryPathList = new List<string>();

                DirectoryInfo _directoryInfo = new DirectoryInfo(strDirPath);
                foreach (FileSystemInfo _fi in _directoryInfo.GetFileSystemInfos())
                {
                    if (_fi is DirectoryInfo)
                    {
                        if ((_fi.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            continue;
                        }
                        _directoryPathList.Add(_fi.FullName);

                    }
                }

                return _directoryPathList;
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            return Path.Combine(AppContext.BaseDirectory, strPath);

        }

        /// <summary>
        /// 获取文件所在文件夹
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <returns></returns>
        public static string GetFileDirectoryName(string strPath)
        {
            return Path.GetDirectoryName(strPath);
        }

        /// <summary>
        /// 获取不含后缀的文件名
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <returns></returns>
        public static string GetFileName(string strPath)
        {
            return Path.GetFileNameWithoutExtension(strPath);
        }

        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <returns></returns>
        public static string GetFileExt(string strPath)
        {
            return Path.GetExtension(strPath).Replace(".", "");
        }

        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static long GetFileSize(string path)
        {
            System.IO.FileInfo fileInfo = null;
            try
            {
                fileInfo = new System.IO.FileInfo(path);
            }
            catch
            {
                // 其他处理异常的代码
            }
            if (fileInfo != null && fileInfo.Exists)
            {
                return fileInfo.Length;
            }
            return 0;
        }

        /// <summary>
        /// 获取文件最后修改时间
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static DateTime GetFileModifiedTime(string path)
        {
            System.IO.FileInfo fileInfo = null;
            try
            {
                fileInfo = new System.IO.FileInfo(path);
            }
            catch
            {
                // 其他处理异常的代码
            }
            if (fileInfo != null && fileInfo.Exists)
            {
                System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(path);
                return fileInfo.LastWriteTimeUtc;
            }
            return DateTime.MinValue;
        }


        /// <summary>
        /// 设置文件最后修改时间
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="dt">修改到的时间</param>
        public static void SetFileModifiedTime(string path, DateTime dt)
        {
            if (File.Exists(path))
            {
                File.SetLastWriteTimeUtc(path, dt);
            }


        }

        public enum ShowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_FORCEMINIMIZE = 11,
            SW_MAX = 11
        }
        [System.Runtime.InteropServices.DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);


        /// <summary>
        /// 执行文件
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <param name="param">运行参数</param>
        /// <returns></returns>
        public static bool RunFile(string path, string param)
        {
            string _filedir = GetFileDirectoryName(path) + "\\";
            IntPtr i = ShellExecute(IntPtr.Zero, "open", path.Replace(_filedir, ""), param, _filedir, ShowCommands.SW_SHOWNORMAL);
            return (int)i >= 32;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static void DeleteFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        /// <summary>
        /// 读取文件文本内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string FileTextRead(string filePath)
        {
            //判断文件是否存在
            if (!File.Exists(filePath))
            {
                return "";
            }

            return File.ReadAllText(filePath, new System.Text.UTF8Encoding());
        }

        /// <summary>
        /// 创建文本文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileText">文件内容</param>
        public static void FileTextWrite(string filePath, string fileText)
        {
            string _dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(_dir))
            {
                Directory.CreateDirectory(_dir);
            }
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.AppendAllText(filePath, fileText, new System.Text.UTF8Encoding());
        }

        /// <summary>
        /// 在文件尾部添加文本内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fileText">文件内容</param>
        public static void FileTextAdd(string filePath, string fileText)
        {
            string _dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(_dir))
            {
                Directory.CreateDirectory(_dir);
            }
            File.AppendAllText(filePath, fileText, new System.Text.UTF8Encoding());
        }


        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string FileMD5(string filePath)
        {
            string md5Str = string.Empty;
            // 判断文件是否存在
            if (!File.Exists(filePath))
            {
                return md5Str;
            }

            try
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(filePath))
                    {
                        md5Str = BitConverter.ToString(md5.ComputeHash(stream));
                        stream.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return md5Str;
        }


        //复制文件夹
        public static void CopyDirectory(string sourceDir, string targetDir)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDir);
            DirectoryInfo[] dirs = dir.GetDirectories();

            // If the source directory does not exist, throw an exception.
            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {sourceDir}");
            }

            // If the destination directory does not exist, create it.
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string tempPath = Path.Combine(targetDir, file.Name);
                file.CopyTo(tempPath, true);
            }

            // If copying subdirectories, copy them and their contents to the new location.
            foreach (DirectoryInfo subdir in dirs)
            {
                string tempPath = Path.Combine(targetDir, subdir.Name);
                CopyDirectory(subdir.FullName, tempPath);
            }
        }


    }


    /// <summary>
    /// 文件信息类
    /// </summary>
    public class FileData
    {
        /// <summary>
        /// 文件完整路径
        /// </summary>
        public string FileName { get; set; } = string.Empty;

        /// <summary>
        /// 文件大小
        /// </summary>
        public long FileSize { get; set; } = -1;

        /// <summary>
        /// 文件最后修改时间
        /// </summary>
        public DateTime LastUpdateTime { get; set; } = DateTime.MinValue;
    }

}
